package com.catjiu.wangEditor.entity;

import java.util.regex.Pattern;

public class Color {
    private int r;
    private int g;
    private int b;

    public Color() {
    }

    public Color(int r, int g, int b) {
        this.r = r;
        this.g = g;
        this.b = b;
    }

    public Color(String rgb) {
        rgb = rgb.substring(rgb.indexOf("(")+1);
        rgb = rgb.substring(0,rgb.indexOf(")"));
        String[] cs = rgb.split(",");
        r = Integer.parseInt(cs[0].trim());
        g = Integer.parseInt(cs[1].trim());
        b = Integer.parseInt(cs[2].trim());
    }


    /**
     * RGB颜色 转 HEX颜色
     * @return
     */
    public String toHEX() {
        if (r < 0 || r > 255 || g < 0 || g > 255 || b < 0
                || b > 255) {
            return "";
        }
        String redStr = Integer.toHexString(r);
        String greenStr = Integer.toHexString(g);
        String blueStr = Integer.toHexString(b);
        return (redStr + greenStr + blueStr).toUpperCase();
    }

    public static Color toColor(String hex){
        Color rgb = new Color();
        if(!Pattern.matches("^#[0-9a-f[A-F]]{6}", hex)){
            return rgb;
        }
        String redStr = hex.substring(1,3);
        String greenStr = hex.substring(3,5);
        String blueStr = hex.substring(5);
        rgb.r = Integer.valueOf(redStr, 16);
        rgb.g = Integer.valueOf(greenStr, 16);
        rgb.b = Integer.valueOf(blueStr, 16);
        return rgb;
    }
    @Override
    public String toString() {
        return "rgb("+r+","+g+","+b+")";
    }
}
